package com.shopx.core.utils;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.math.NumberUtils;
import org.apache.commons.lang.time.DateFormatUtils;

import java.util.concurrent.atomic.AtomicInteger;

public class IDUtils {
	
	public static AtomicInteger CURRENT_SEQ = new AtomicInteger(0);

	/**
	 * 17位时间戳yyyyMMddHHmmssSSS+6位机器序号999999̨+8位顺序号 + 1校验位(32位）
	 * 17位时间戳（yyyyMMddHHmmssSSS）+6位机器（999999台）+ 8位顺序号 + 1位校验位  (32位）
	 * @return
	 */
	public static String getId32(String mchineId) {
		//--
		//-- 
		//-- 
		long tm = System.currentTimeMillis();
		String stm = DateFormatUtils.format(tm, "yyyyMMddHHmmssSSS");
		//String mchineId = EncrypConfigure.getProperty("machine.id");
		int seq = CURRENT_SEQ.addAndGet(1);
		
		//--  有并发控制问题? 加锁？
		//TODO 
		if (seq >= 99999999) {
			CURRENT_SEQ = new AtomicInteger(0);
			seq = CURRENT_SEQ.addAndGet(1);
		}
		String strSeq = StringUtils.leftPad(String.valueOf(seq), 8, '0');
		
		return cacl(stm+mchineId+strSeq);
	}
	
	/**
	 * 17位时间戳 + 6位机器号 + 
	 * @return
	 */
	public static String getId64() {
		
		return null;
	}
	
	
	private static String cacl(String src) {
		char[] srcArr = src.toCharArray();

		int n = 0;
		for (int i = 0; i < srcArr.length; i++) {
			String t = String.valueOf(srcArr[i]);
			int m = NumberUtils.toInt(t);

			if ((i + 1) % 2 == 0) {
				String strM = Integer.toString(m * 2);
				char[] strArr = strM.toCharArray();

				for (int j = 0; j < strArr.length; j++) {
					String t0 = String.valueOf(strArr[j]);
					int k = NumberUtils.toInt(t0);
					n = n + k;
				}
			} else {
				n = n + m;
			}
		}

		String dst = "";
		if (n % 10 == 0) {
			dst = "0";
		} else {
			int j = n / 10 + 1;
			j = j * 10;
			dst = String.valueOf(j - n);
		}

		return src = src + dst;
	}
}
